package config

import (
	"log"
	"os"
	"strings"

	"gopkg.in/yaml.v3"
)

var GlobalConfig *Config

// Init 初始化配置
func Init() {
	// 读取配置文件
	data, err := os.ReadFile("config/config.yaml")
	if err != nil {
		log.Fatal("Failed to read config file:", err)
	}

	// 替换环境变量
	content := string(data)
	content = replaceEnvVars(content)

	// 解析YAML配置
	GlobalConfig = &Config{}
	if err := yaml.Unmarshal([]byte(content), GlobalConfig); err != nil {
		log.Fatal("Failed to parse config file:", err)
	}

	// 初始化数据库配置
	DbCfg.DbUser = GlobalConfig.Database.Username
	DbCfg.DbPass = GlobalConfig.Database.Password
	DbCfg.DbHost = GlobalConfig.Database.Host
	DbCfg.DbPort = GlobalConfig.Database.Port
	DbCfg.DbName = GlobalConfig.Database.Database

	// 初始化HTTP配置
	HttpCfg.Listen = GlobalConfig.Server.Host
	HttpCfg.Port = GlobalConfig.Server.Port

	// 初始化Redis配置
	RedisConf.Network = "tcp"
	RedisConf.Address = GlobalConfig.Redis.Host + ":" + GlobalConfig.Redis.Port
	RedisConf.Password = GlobalConfig.Redis.Password
	RedisConf.DB = GlobalConfig.Redis.DB

	// 初始化应用配置
	RunCFG.UserPassExt = GlobalConfig.App.UserPassExt
	RunCFG.RequestLogFile = GlobalConfig.App.RequestLogFile
	RunCFG.ErrorLogFile = GlobalConfig.App.ErrorLogFile
	RunCFG.ServiceStartLogFile = GlobalConfig.App.ServiceStartLogFile
	RunCFG.SessionTime = GlobalConfig.App.SessionTime

	// 初始化Elasticsearch配置
	EsConf["URL"] = GlobalConfig.Elastic.URL
	EsConf["INDEX_NAME_POST"] = GlobalConfig.Elastic.IndexNamePost
	EsConf["INDEX_NAME_ACCESS"] = GlobalConfig.Elastic.IndexNameAccess
}

// replaceEnvVars 替换环境变量
func replaceEnvVars(content string) string {
	// 查找 ${VAR:default} 格式的环境变量
	start := 0
	for {
		start = strings.Index(content[start:], "${")
		if start == -1 {
			break
		}
		start += 2

		end := strings.Index(content[start:], "}")
		if end == -1 {
			break
		}

		envVar := content[start : start+end]
		parts := strings.SplitN(envVar, ":", 2)

		var value string
		if len(parts) == 2 {
			// 有默认值
			value = os.Getenv(parts[0])
			if value == "" {
				value = parts[1]
			}
		} else {
			// 没有默认值
			value = os.Getenv(envVar)
		}

		// 替换
		content = content[:start-2] + value + content[start+end+1:]
	}

	return content
}

// GetConfig 获取全局配置
func GetConfig() *Config {
	return GlobalConfig
}
